import message from '@wanhu/antd-legacy/lib/message';
import { Button, Checkbox, Col, Input, Modal, Row, Select, Icon } from 'antd';
import { cloneDeep, debounce } from 'lodash';
import moment from 'moment';
import React, { Component } from 'react';
import api from '../../../api/api';
import history from '../../../history';
import { connectRouter } from '../../../mixins/router';
import { connect as connectState } from '../../../states/insurance/insuranceOrderList';
import { DateRangePicker } from '../../common/DateRangePicker';
import { Form } from '../../common/form';
import HasPermission, { testPermission } from '../../common/HasPermission';
import { TablePage } from '../../common/table-page';
// 会员卡片弹窗
import CustomerCart from '../../customerCenter/CustomerCard';
// 订单问询激活弹窗
import ActivateModal from './activateModal.jsx';
import './index.css';
import { markIdCard, markPhoneNumber } from '../../../../src/utils';
const TableColumn = TablePage.Column;
const Option = Select.Option;

const QueryKeyChoices = [
  {
    value: '1',
    label: '服务对象',
  },
  {
    value: '5',
    label: '购买人',
  },
  {
    value: '2',
    label: '对象身份证号',
  },
  {
    value: '4',
    label: '销售渠道码',
  },
  {
    value: '3',
    label: '会员服务单',
  },
];

const isPayStatusChoices = [
  { value: '0', label: '待支付' },
  { value: '1', label: '已支付' },
  { value: '2', label: '支付失败' },
];

const payType = [
  { value: '1', label: '年缴' },
  { value: '2', label: '月缴' },
  { value: '3', label: '季缴' },
];

const orderTypes = [
  { value: '2', label: '待激活' },
  { value: '3', label: '服务中' },
  { value: '4', label: '已完成' },
  { value: '6', label: '已终止' },
];

const mapChoiceToOption = (choice, i) => (
  <Select.Option key={i} value={choice.value}>
    {choice.label}
  </Select.Option>
);

const tableDef = TablePage.def({
  type: {
    parse: (val) => val || '1',
    stringify: (val) => (val === '1' ? undefined : val),
  },
  search: {},
  // packageId: {},
  packageName: '',
  payWay: {},
  startTime: {
    parse: (val) =>
      val
        ? val.split(',').map((s) => {
            if (!s) return undefined;
            const m = moment(s);
            return m.isValid() ? m : undefined;
          })
        : undefined,
    stringify: (val) =>
      val ? val.map((d) => (d && moment.isMoment(d) ? d.format('YYYY-MM-DD') : '')).join(',') : undefined,
  },
  payStatus: {},
  status: {},
  canReason: '',
});

// 获取URL参数
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

let win; // window.open 打开的窗口对象

// 环境区分
function envType() {
  const host = location.host;
  let inquiryLink;
  let e;

  if (host === 't.crm.wanhuhealth.com' || host === 't-crm.wanhuhealth.com') {
    inquiryLink = 'https://d-bx.wanhuhealth.com/common/index.html';
    e = 't';
  } else if (host === 'demo-crm.wanhuhealth.com') {
    inquiryLink = 'https://d-bx.wanhuhealth.com/common/index.html';
    e = 'd';
  } else if (host === 'localhost:7003') {
    inquiryLink = 'https://d-bx.wanhuhealth.com/common/index.html';
    // inquiryLink = 'http://192.168.1.246:8080/common/index.html';
    e = 't';
  } else {
    inquiryLink = 'https://bx.wanhuhealth.com/common/index.html';
    e = 'p';
  }

  return {
    inquiryLink,
    e,
  };
}

function getCookie(key) {
  //以分号分割cookie并返回一个数组
  var res = document.cookie.split(';');
  for (let i = 0; i < res.length; i++) {
    var temp = res[i].split('=');
    if (temp[0].trim() === key) {
      return temp[1];
    }
  }
}

class InsuranceOrder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      insurId: null,
      confirmDate: null,
      confirmDateExplain: null,
      canshow: false,
      packageId: undefined,
      customerCardVisible: false,
      currentCustomerId: null,
      activateModalShow: false, // 激活弹窗是否展示
      orderInfo: null, // 需要激活的订单信息
      enquiryList: [], // 问询列表
      canReason: '',
      resultTitle: '激活成功', // 激活结果弹窗title
    };
  }
  componentWillReceiveProps(props) {
    this.setState({
      packageId: undefined,
    });
    if (this.props.router.modal === 'insuranceOrder' && !props.router.modal) {
      this.table.reload();
    }
  }
  async componentDidMount() {
    if (getQueryVariable('buyServiceStatus') && getQueryVariable('teamOrderNo')) {
      if (getQueryVariable('buyServiceStatus') === '0') {
        try {
          const data = await api.insureInsureOrderNo(getQueryVariable('teamOrderNo'), []);
          if (data) {
            message.success('激活成功');
          } else {
            message.error('激活失败');
          }
          setTimeout(() => {
            this.table.reload();
          }, 100);
        } catch (error) {
          // message.error(error.message || '已经激活过，不需要重新激活');
          setTimeout(() => {
            window.location.href = '/patientInsurance';
          }, 100);
        }
      } else {
        message.error('激活失败');
      }
    }

    this.setState({
      packageId: undefined,
    });
    const list = await api.getInsuracePackageSummary();
    this.setState({
      insurancePackage: [...list],
      insurancePackage2: cloneDeep(list),
    });
    setTimeout(() => {
      this.setState({
        packageId: undefined,
      });
    }, 0);

    // 监听postmess消息
    window.addEventListener('message', this.postMsg, false);
  }
  componentWillUnmount() {
    this.props.resetInsurancesOrderList();
    window.removeEventListener('message', this.postMsg, false);
  }

  loadData = ({ values, pageIndex, pageSize }) => {
    const where = {};
    if (values.startTime && values.startTime.length > 0) {
      if (values.startTime[0]) {
        where.startDate = values.startTime[0].format('YYYY-MM-DD');
      }
      if (values.startTime[1]) {
        where.endDate = values.startTime[1].format('YYYY-MM-DD');
      }
    }
    where.type = values.type;
    let search = values.search;
    where.search = search ? search.replace(/\s*/g, '') : null;
    if (typeof values.packageId === 'string' || !values.packageId) {
      where.packageIds = values.packageId;
    } else {
      where.packageIds = values.packageId.join();
    }
    where.status = values.status;
    where.payWay = values.payWay;
    where.payStatus = values.payStatus;
    where.packageName = values.packageName;
    this.props.searchInsurancesOrderList(where, pageIndex, pageSize);
  };

  resetData = () => {
    this.props.resetInsurancesOrderList();
  };

  openNewOrderInsuranceModal = () => {
    this.props.router.openModal('newPatientInsurance');
  };
  exportData = (values) => {
    const where = {};
    if (values.startTime && values.startTime.length > 0) {
      if (values.startTime[0]) {
        where.startDate = values.startTime[0].format('YYYY-MM-DD');
      }
      if (values.startTime[1]) {
        where.endDate = values.startTime[1].format('YYYY-MM-DD');
      }
    }
    where.type = values.type;
    let search = values.search;
    where.search = search ? search.replace(/\s*/g, '') : null;
    if (typeof values.packageId === 'string' || !values.packageId) {
      where.packageIds = values.packageId;
    } else {
      where.packageIds = values.packageId.join();
    }
    where.status = values.status;
    where.payWay = values.payWay;
    where.payStatus = values.payStatus;
    where.packageName = values.packageName;

    // let exportFile = api.exportInsuranceData(values)
    let valueStr = '';
    for (let item in where) {
      if (where[item]) {
        valueStr += item + '=' + encodeURIComponent(where[item]) + '&';
      }
    }
    window.open(`/_api/patient/insurance_order/export?${valueStr}`, '_blank');
  };

  showDetail = (insurance) => {
    history.push(`/patientInsuranceDetail/${insurance.orderId}?r=${encodeURIComponent(this.props.router.fullPath)}`);
  };

  updateInsurance = (insurance) => {
    this.props.router.openModal('newPatientInsurance', insurance.insurId);
  };

  openConfirmModal = (insurance) => {
    this.setState({ visible: true, insurId: insurance.insurId });
  };

  cancelInsurance = (insurance) => {
    Modal.confirm({
      title: `该操作不可撤销，且被作废的投保单号不可再用。确认作废吗？`,
      onOk: () => {
        this.props.cancelGroupInsurance(insurance.insurId);
      },
      onCancel() {},
    });
  };

  insuranceConfirmation = () => {
    const { insurId, confirmDate } = this.state;
    if (!confirmDate) {
      this.setState({ confirmDateExplain: '不能为空' });
    } else {
      this.props.confirmGroupInsurance(insurId, confirmDate);
      this.setState({
        visible: false,
        confirmDate: null,
        insurId: null,
        confirmDateExplain: '',
      });
    }
  };

  finishConfirmStatus = () => {
    message.success('承保确认成功', 3);
    this.table.reload({ scrollToTop: false });
  };
  finishCancelStatus = () => {
    message.success('投保单已作废', 3);
    this.table.reload({ scrollToTop: false });
  };

  onCheckChange(e) {
    this.setState({
      ischeck: e.target.checked,
    });
  }

  judgeTime(time) {
    var strtime = time.replace(/\-/g, '/'); //时间转换
    //时间
    var date1 = new Date(strtime);
    //现在时间
    var date2 = new Date();
    //判断时间是否过期
    return date1 < date2 ? true : false;
  }

  // 退款原因赋值
  reasonChange(e) {
    e.persist();
    this.setState({
      canReason: e.target.value,
    });
  }

  renderModal() {
    const { canshow, selectOrder, ischeck } = this.state;
    const nowdata = this.props.getInsuranceRevokeOrderInfo;
    let ast = null;
    if (nowdata.status == 'fulfilled') {
      ast = nowdata.payload;
    }

    let isover = false; // 是否超出犹豫期
    let judBtn = () => false;

    if (ast) {
      // 判断是否超出犹豫期(只有保险有犹豫期限制)
      // 是否含有保险,type=1
      const isInclude = ast.products.some((item) => item.productType === 1);
      if (isInclude) {
        isover = ast && ast.deadline ? this.judgeTime(ast.deadline) : false;
      }

      judBtn = () => {
        let b = '';
        if (ast.orderStatus === 2) {
          b = false;
        } else {
          if (isover) {
            b = true;
          } else {
            b = ast.isUse;
          }
        }

        if (b && !this.state.canReason) {
          return true;
        } else {
          return false;
        }
      };
    } else {
      return false;
    }

    const refDom = () => {
      return (
        <div>
          <Row style={{ marginBottom: 15 }}>
            <Col>
              <Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '8px' }} />
              <b>该服务订单正常流程已不许撤单, 是否继续撤单?</b>
            </Col>
          </Row>

          {ast.payments &&
            ast.payments.length &&
            ast.payments.map((i, index) => {
              return (
                <Row key={index}>
                  <Col span={10}>{`${i.paymentTypeName}`}</Col>
                  <Col span={6}>
                    {i.amount}
                    {i.paymentName == 'self_pbm_points_deduction' ? '积分' : '元'}
                    (扣{i.deductAmount}
                    {i.paymentName == 'self_pbm_points_deduction' ? '分' : '元'})
                  </Col>
                </Row>
              );
            })}
          <div style={{ marginTop: '15px' }}>
            <b style={{ color: 'red' }}>*</b>撤单原因:
          </div>
          <Input
            type="textarea"
            autosize={{ minRows: 2, maxRows: 4 }}
            placeholder="请输入撤单原因(最大输入20个汉字)"
            maxLength="20"
            onChange={(e) => this.reasonChange(e)}
          />
        </div>
      );
    };
    const renderText = () => {
      if (ast) {
        /**
         * 待激活状态
         */
        if (ast.orderStatus === 2) {
          return (
            <Row style={{ marginBottom: 15 }}>
              <Col>
                <Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '8px' }} />
                <b>是否确认撤单?</b>
              </Col>
            </Row>
          );
        }

        /**
         * 服务中状态
         */
        if (isover) {
          // 服务订单服务中--保险已过犹豫期，无需判断其他条件,不允许撤单
          return refDom();
        } else {
          // 服务订单服务中--保险在犹豫期内
          if (ast.isUse) {
            // 服务是否使用中
            return refDom();
          } else {
            return (
              <Row style={{ marginBottom: 15 }}>
                <Col>
                  <Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '8px' }} />
                  <b>是否确认撤单?</b>
                </Col>
              </Row>
            );
          }
        }
      }
    };

    return (
      <Modal
        title="撤单确认"
        visible={canshow}
        width={500}
        maskClosable={false}
        onCancel={this.hideModal.bind(this)}
        style={{ backgroundColor: '#f8f8f8' }}
        footer={
          <Row>
            <Button onClick={this.submit.bind(this)} type="primary" disabled={judBtn()} loading={false}>
              确认撤单
            </Button>
            <Button onClick={this.hideModal.bind(this)} className="cancelButton">
              取消
            </Button>
          </Row>
        }
      >
        {renderText()}
      </Modal>
    );
  }

  // 撤单
  revocationOrder(data) {
    this.props.getInsuranceRevokeOrderList(data.orderId);
    this.setState({
      canshow: true,
      selectOrder: data,
    });
  }

  // 是否展示激活按钮
  showActivateBtn(pool, status) {
    return (
      testPermission('insurance.edit') &&
      pool.payStatus === 1 &&
      (status === 2 || (pool.teamOrderNo && pool.healthEnquiry === false)) &&
      pool.needInquiry
    );
  }

  // 点击列表激活
  async activate(data) {
    // 获取订单是否需要问询
    const inquiryData = await api.getInsuranceInquiries(data.insurancePackageId);
    if (inquiryData && inquiryData.needInquiry) {
      // inquiryData.inquiryType === 1 ? 第三方问询 : 本地问询
      if (inquiryData.inquiryType) {
        // 第三方问询避免数据同步失败, 激活前先同步数据, 如果返回true,代表已激活成功,如果返回false,则需要跳转重新激活
        const result = await api.insureInsureOrderNo(data.teamOrderNo, []);
        if (result) {
          message.success('激活成功');
          setTimeout(() => {
            this.table.reload();
          }, 100);
        } else {
          // 获取订单详情
          const insuranceOrderInfo = await api.getOriginInsuranceOrderInfo(data.orderId);
          // 保险公司编码
          let productGradeCode = '';
          let { orderProduct = [] } = insuranceOrderInfo;
          if (orderProduct) {
            for (let i = 0; i < orderProduct.length; i++) {
              if (orderProduct[i].productType === 1) {
                productGradeCode = orderProduct[i].productGradeCode;
                break;
              }
            }
          }
          let href =
            location.origin + '/patientInsurance' + `?orderId=${data.orderNo}&teamOrderNo=${data.teamOrderNo}&a=1`;

          href = encodeURIComponent(href);

          const url = `${inquiryData.inquiryUrl}?name=${data.insuredName}&cardNo=${data.insuredIdCard}&productGradeCode=${productGradeCode}&orderId=${data.teamOrderNo}&returnUrl=${href}`;
          // const url = `https://uat-channelh5.pubmi.cn/normalProduct/housepopup?name=雷海彦&cardNo=11010119661109673X&orderId=vpo2020110900000883&returnUrl=${encodeURIComponent(href)}`
          window.location.href = url;
        }
      } else {
        this.setState({
          orderInfo: data,
        });
        const inquiryLink = `${envType().inquiryLink}?e=${envType().e}&packageId=${
          data.insurancePackageId
        }&serviceName=&teamOrderNo=${data.teamOrderNo}&token=${getCookie('token')}`;
        const l = (document.body.clientWidth - 540) / 2;
        win = window.open(
          inquiryLink,
          '健康问询',
          `width=540,height=720,left=${l},top=${60}menubar=no,toolbar=no,location=no,directories=no,status=no`,
        );
      }
    }
  }

  // postMessage消息处理
  postMsg = async (event) => {
    const { data } = event;
    win.close();
    win = null;
    this.setState({
      activateModalShow: true,
      resultTitle: '激活成功',
    });

    const res = await api.insureInsureOrderNoV2(this.state.orderInfo.teamOrderNo, data);
    if (res.data) {
      this.setState({
        activateModalShow: true,
        resultTitle: '激活成功',
      });
    } else {
      this.setState({
        activateModalShow: true,
        resultTitle: '激活失败',
      });
    }
  };

  // 问询弹窗关闭
  activateCancel = () => {
    this.setState({
      activateModalShow: false,
      orderInfo: null,
    });
    setTimeout(() => {
      this.table.reload();
    }, 300);
  };

  submit() {
    this.props.subRevokeOrderRes({
      orderId: this.state.selectOrder.orderId,
      canReason: this.state.canReason ? this.state.canReason : '正常撤单',
    });
    this.setState({
      canshow: false,
      ischeck: false,
      canReason: '',
    });
    setTimeout(() => {
      this.table.reload();
    }, 300);
  }

  checkOrder(item) {
    history.push(`/patientRevokeOrderDetail/${item.orderId}?r=${encodeURIComponent(this.props.router.fullPath)}`);
    this.setState({
      canshow: false,
    });
  }

  hideModal() {
    this.setState({
      canshow: false,
      ischeck: false,
      canReason: '',
    });
  }

  checkPayOrder(data) {
    Modal.confirm({
      title: `请确认该订单已有线下现金支付完成，现金支付金额：${data.amount}元？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        this.props.cancelGroupInsurance(data.insurId);
      },
      onCancel() {},
    });
  }

  // 搜索时
  searchPageName = (value, opt) => {
    const str = opt.props.children.join('').toLocaleLowerCase();
    if (str.indexOf(value.toLocaleLowerCase()) >= 0) {
      return true;
    } else {
      return false;
    }
  };

  // 显示会员卡片
  showCustomerCard = (id) => {
    this.setState({
      customerCardVisible: true,
      currentCustomerId: id,
    });
  };
  hideCustomerCard = () => {
    this.setState({
      customerCardVisible: false,
    });
  };
  render() {
    const { insurancePackage } = this.state;
    const options =
      insurancePackage &&
      insurancePackage.map((item, index) => {
        return (
          <Option key={item.packageId}>
            {item.insurancePackageName}({item.packageCode})
          </Option>
        );
      });

    const children = [];
    for (let i = 10; i < 36; i++) {
      children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
    }
    return (
      <div className="insurance_orderList">
        <CustomerCart
          id={this.state.currentCustomerId}
          visible={this.state.customerCardVisible}
          hideCustomerCard={this.hideCustomerCard}
        ></CustomerCart>
        <TablePage
          def={tableDef}
          data={this.props.insurancesOrderList}
          autoLoad={false}
          onLoadData={this.loadData}
          onExportData={this.exportData}
          onResetData={this.resetData}
          tableRef={(table) => (this.table = table)}
          rowKey="insurId"
          renderFormFields={(values, loadData, setValues, exportData) => {
            let searchProps;
            switch (values.type) {
              case '1':
                searchProps = { placeholder: '请输入服务对象' };
                break;
              case '3':
                searchProps = { placeholder: '请输入会员服务单' };
                break;
              case '2':
                searchProps = { placeholder: '请输入对象身份证号' };
                break;
              case '4':
                searchProps = { placeholder: '请输入销售渠道码' };
                break;
              case '5':
                searchProps = { placeholder: '请输入购买人' };
                break;
              default:
                searchProps = { disabled: true };
                break;
            }
            return (
              <Row gutter={8} className="block filter-box">
                <Col span={3} key="1">
                  <Form.Item field="type" height="auto">
                    <Select>{QueryKeyChoices.map(mapChoiceToOption)}</Select>
                  </Form.Item>
                </Col>
                <Col span={3} key="2">
                  <Form.Item field="search" height="auto">
                    <Input {...searchProps} onPressEnter={loadData} />
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Form.Item field="packageName" height="auto">
                    <Input placeholder="请输入服务包名称或编码" onPressEnter={loadData} />
                  </Form.Item>
                </Col>
                {/* <Col span={5}>
                  <Form.Item field="packageId" height="auto">
                    <Select
                      mode="multiple"
                      placeholder="请输入服务包名称(可多选)"
                      filterOption={this.searchPageName}
                      notFoundContent={null}
                      allowClear
                    >
                      {options}
                    </Select>
                  </Form.Item>
                </Col> */}
                <Col span={2}>
                  <Form.Item field="status" height="auto">
                    <Select placeholder="请选择订单状态" allowClear>
                      {orderTypes.map(mapChoiceToOption)}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={2}>
                  <Form.Item field="payStatus" height="auto">
                    <Select placeholder="请选择支付状态" allowClear>
                      {isPayStatusChoices.map(mapChoiceToOption)}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={3}>
                  <Form.Item field="startTime" height="auto">
                    <DateRangePicker size="default" placeholder="请选择登记时间" />
                  </Form.Item>
                </Col>
                <Col span={2}>
                  <Button onClick={loadData} style={{ width: '100%', minWidth: 0 }} type="primary">
                    查询
                  </Button>
                </Col>
                <Col span={2}>
                  <HasPermission match="insurance.edit">
                    <Button
                      onClick={this.openNewOrderInsuranceModal}
                      style={{ width: '100%', minWidth: 0 }}
                      type="primary"
                    >
                      新建
                    </Button>
                  </HasPermission>
                </Col>
                <Col span={2}>
                  <HasPermission match="insurance.order.export">
                    <Button onClick={exportData} style={{ width: '100%', minWidth: 0 }} type="primary">
                      导出
                    </Button>
                  </HasPermission>
                </Col>
              </Row>
            );
          }}
        >
          <TableColumn
            title="会员服务单号"
            className="singleline max-w-200"
            dataIndex="orderNo"
            key="orderNo"
            onCellClick={this.showDetail}
            render={(text, insurance) => <span className="clickable">{text}</span>}
          />
          <TableColumn
            title="服务对象"
            className="singleline"
            dataIndex="insuredName"
            key="insuredName"
            render={(text, insurance) => (
              <span
                style={{ textDecoration: 'underline', cursor: 'pointer' }}
                onClick={() => {
                  this.showCustomerCard(insurance.insuredId);
                }}
              >
                {text}
              </span>
            )}
          />
          <TableColumn
            title="对象身份证号"
            dataIndex="insuredIdCard"
            key="insuredIdCard"
            render={(text) => <span>{markIdCard(text)}</span>}
          />
          <TableColumn
            title="手机号"
            className="singleline"
            dataIndex="insuredPhone"
            key="insuredPhone"
            render={(text) => <span>{markPhoneNumber(text)}</span>}
          />
          <TableColumn
            title="会员服务包"
            className="singleline"
            dataIndex="insurancePackageName"
            key="insurancePackageName"
          />
          <TableColumn title="服务包编码" className="singleline" dataIndex="insurancePackageCode" />
          <TableColumn
            title="服务档次"
            className="singleline"
            dataIndex="insurancePackageGradeName"
            key="insurancePackageGradeName"
          />
          <TableColumn
            title="订单状态"
            className="singleline"
            dataIndex="status"
            key="status"
            render={(status, insurance) => {
              if (status === null || status === undefined) return '';
              const found = orderTypes.find((t) => t.value == `${status}`);
              if (found) {
                return <span>{found.label}</span>;
              }
              return <span>未知状态</span>;
            }}
          />
          <TableColumn
            title="缴费方式"
            className="singleline"
            dataIndex="payWay"
            key="payWay"
            render={(status, insurance) => {
              if (status === null || status === undefined) return '';
              const found = payType.find((t) => t.value == `${status}`);
              if (found) {
                return <span>{found.label}</span>;
              }
              return <span>未知方式</span>;
            }}
          />
          <TableColumn
            title="支付状态"
            className="singleline"
            dataIndex="payStatus"
            key="payStatus"
            render={(payStatus, insurance) => {
              if (payStatus === null || payStatus === undefined) return '';
              const found = isPayStatusChoices.find((t) => t.value == `${payStatus}`);
              if (found) {
                return (
                  <span>
                    {found.label}
                    {insurance.payWay == 2 ? insurance.period : ''}
                  </span>
                );
              }
              return <span>未知状态</span>;
            }}
          />
          <TableColumn title="购买人" className="singleline" dataIndex="insurerName" />
          <TableColumn title="销售渠道" className="singleline" dataIndex="channelCode" />
          <TableColumn title="登记时间" className="singleline" dataIndex="orderDate" key="orderDate" />

          <TableColumn
            title="操作"
            className="singleline"
            dataIndex="status"
            key="op"
            renderTip={() => null}
            render={(status, pool) => {
              let toggleBtn;
              if (status == 1 || status == 2 || status == 0 || status == 3) {
                toggleBtn = (
                  <span>
                    {testPermission('insurance.revoke') ? (
                      <span className="clickable" onClick={() => this.revocationOrder(pool)}>
                        撤单
                      </span>
                    ) : null}
                    {this.showActivateBtn(pool, status) ? (
                      <span className="clickable" onClick={() => this.activate(pool)}>
                        激活
                      </span>
                    ) : null}
                  </span>
                );
              } else if (status == 6) {
                toggleBtn = (
                  <span>
                    <span className="clickable" onClick={() => this.checkOrder(pool)}>
                      查看退款单
                    </span>
                  </span>
                );
              }
              return toggleBtn;
            }}
          />
        </TablePage>
        {this.renderModal()}

        {/* 问询弹窗 */}
        {this.state.orderInfo ? (
          <ActivateModal
            show={this.state.activateModalShow}
            orderInfo={this.state.orderInfo}
            title={this.state.resultTitle}
            enquiryList={this.state.enquiryList}
            onCancel={this.activateCancel}
          />
        ) : null}
      </div>
    );
  }
}

export default connectRouter(connectState(InsuranceOrder));
